import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_splash_screen/flutter_splash_screen.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:kk/dao/home_dao.dart';
import 'package:kk/model/common_model.dart';
import 'package:kk/pages/search_page.dart';
import 'package:kk/widget/grid_nav.dart';
import 'package:kk/widget/loading_container.dart';
import 'package:kk/widget/local_nav.dart';
import 'package:kk/widget/sales_box.dart';
import 'package:kk/widget/search_bar.dart';
import 'package:kk/widget/sub_nav.dart';
import 'package:kk/widget/webview.dart';

const alpha_offset = 100;
const SEARCH_BAR_DEFAULT_TEXT = "网红打卡地 景点 酒店 美食";

class HomePage extends StatefulWidget {
  const HomePage();

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double _appBarAlpha = 0;
  List<CommonModel> localNavList = [];
  List<CommonModel> subNavList = [];
  List<CommonModel> bannerList = [];
  dynamic gridNavModel;
  dynamic salesBox;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _handleRefesh();
    Future.delayed(Duration(milliseconds:600),(){
      FlutterSplashScreen.hide();
    });
  }

  Future<Null> _handleRefesh() async {
    HomeDao.fetch().then((value) {
      setState(() {
        bannerList = value!.bannerList;
        localNavList = value.localNavList;
        gridNavModel = value.gridNav;
        subNavList = value.subNavList;
        salesBox = value.salesBox;
        _loading = false;
      });
    }).catchError((e) {
      setState(() {
        _loading = false;
      });
    });
    return null;
  }

  void _onScroll(double pixels) {
    double alpha = pixels / alpha_offset;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      _appBarAlpha = alpha;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xf2f2f2),
      body: LoadingContainer(
          isLoading: _loading,
          child: Stack(
            children: [
              MediaQuery.removePadding(
                  removeTop: true,
                  context: context,
                  child: RefreshIndicator(
                      onRefresh: _handleRefesh,
                      child: NotificationListener(
                          onNotification: (notification) {
                            if (notification is ScrollUpdateNotification &&
                                notification.depth == 0) {
                              _onScroll(notification.metrics.pixels);
                            }
                            return false;
                          },
                          child: _listView))),
              _appBar,
            ],
          )),
    );
  }

  Widget get _listView {
    return ListView(
      children: [
        _banner,
        Padding(
          padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: LocalNav(localNavList: localNavList),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: GridNav(gridNavModel: gridNavModel),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SubNav(subNavList: subNavList),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SalesBox(salesBox: salesBox),
        ),
      ],
    );
  }

  Widget get _banner {
    return Container(
      height: 160,
      child: Swiper(
        itemCount: bannerList.length,
        autoplay: true,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                CommonModel model = bannerList[index];
                final title = model.title;
                return WebView(
                  url: model.url,
                  title: title,
                  hideAppBar: model.hideAppBar,
                );
              }));
            },
            child: Image.network(
              bannerList[index].icon,
              fit: BoxFit.fill,
            ),
          );
        },
        pagination: SwiperPagination(),
      ),
    );
  }

  Widget get _appBar {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0x66000000), Colors.transparent],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter)),
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 35, 0, 0),
            height: 80,
            decoration: BoxDecoration(
                color: Color.fromARGB(
                    (_appBarAlpha * 255).toInt(), 255, 255, 255)),
            child: SearchBar(
                defaultText: SEARCH_BAR_DEFAULT_TEXT,
                searchBarType: _appBarAlpha > 0.2
                    ? SearchBarType.homeLight
                    : SearchBarType.home,
                leftButtonClick: () {
                  // Navigator.pop(context);
                },
                speakClick: _jumpToSpeak,
                inputBoxClick: _jumpToSearch),
          ),
        ),
        Container(
          height: _appBarAlpha > 0.2 ? 0.5 : 0,
          decoration: BoxDecoration(
              boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]),
        )
      ],
    );
  }

  void _jumpToSearch() {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return SearchPage(
        hint: SEARCH_BAR_DEFAULT_TEXT,
      );
    }));
  }

  void _jumpToSpeak() {}
}
